/**
 * Copyright &copy; 2016-2017 <a href="http://git.oschina.net/whoamien/backend_management">Backend Management</a> All rights reserved.
 */
package com.xw.app.imageupload;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;

/**
 * The Class AliyunImageUploadMethod.
 *
 * @author Xi Wei
 */
public class AliyunImageUploadMethod implements ImageUploadMethod {

	/* (non-Javadoc)
	 * @see com.xw.app.imageupload.ImageUploadMethod#uploadImage(javax.servlet.http.HttpServletRequest, org.springframework.web.multipart.MultipartFile, java.lang.String, java.lang.String)
	 */
	@Override
	public String uploadImage(HttpServletRequest request, MultipartFile file, String remoteFilePath, String fileName) {
		try {
			return uploadImage(request, file.getInputStream(), remoteFilePath, fileName);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

	/* (non-Javadoc)
	 * @see com.xw.app.imageupload.ImageUploadMethod#uploadImage(javax.servlet.http.HttpServletRequest, java.io.InputStream, java.lang.String, java.lang.String)
	 */
	@Override
	public String uploadImage(HttpServletRequest request, InputStream is, String remoteFilePath, String fileName) {
		try {
			if (!remoteFilePath.endsWith("/")) {
				remoteFilePath += "/";
			}
			OSSConfigure ossConfigure = new OSSConfigure("aliyunoss.properties");
			OSSClient ossClient = new OSSClient(ossConfigure.getEndpoint(), ossConfigure.getAccessKeyId(),
					ossConfigure.getAccessKeySecret());

			// 创建上传Object的Metadata
			ObjectMetadata objectMetadata = new ObjectMetadata();
			objectMetadata.setContentLength(is.available());
			objectMetadata.setCacheControl("no-cache");
			objectMetadata.setHeader("Pragma", "no-cache");
			objectMetadata.setContentType(OSSManageUtil.contentType(fileName.substring(fileName.lastIndexOf("."))));
			objectMetadata.setContentDisposition("inline;filename=" + fileName);
			// 上传文件
			ossClient.putObject(ossConfigure.getBucketName(), remoteFilePath + fileName, is,
					objectMetadata);
			System.out.println(ossConfigure.getAccessUrl() + "/" + remoteFilePath + fileName);
			return ossConfigure.getAccessUrl() + "/" + remoteFilePath + fileName;

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

}
